#include <winsock2.h>
#include <stdio.h>
#include <ws2tcpip.h>
#include <qdebug.h>
#include <thread>
#include <iostream>
#include "GameClient.h"

#pragma comment(lib, "Ws2_32.lib")


GameClient::GameClient(const char* ip, int port, std::function<void(char*)> callback) {
	WSADATA wasData;
	int err;
	WORD wVersionRequested = MAKEWORD(2, 2);
	err = WSAStartup(wVersionRequested, &wasData);
	if (err != 0)
	{
		qDebug() << "WSAStartup errorNum =" << GetLastError();
		return;
	}

	this->clientSocket = socket(AF_INET, SOCK_STREAM, 0);
	if (INVALID_SOCKET == this->clientSocket)
	{
		qDebug() << "create socket failed ! ! !";
		return;
	}

	struct sockaddr_in target;
	target.sin_family = AF_INET;
	target.sin_port = htons(port);
	target.sin_addr.s_addr = inet_addr(ip);

	if (-1 == connect(this->clientSocket, (struct sockaddr*)&target, sizeof(target))) {
		qDebug() << "connect server failed ! ! !";
		closesocket(this->clientSocket);
		return;
	}
	std::thread t([this, callback]() {
		char rbuffer[1024];
		while (TRUE) {
			int ret = recv(clientSocket, rbuffer, 1024, 0);
			if (ret <= 0) break;
			callback(rbuffer);
		}
		closesocket(clientSocket);
		});
	t.detach();

	return;
}


GameClient::~GameClient() {
}

void GameClient::sendBuffer(const char* buffer) {
	qDebug() << "client send:" << buffer;
	send(clientSocket, buffer, strlen(buffer), 0);
}
